//
//  WBNewFeatureView.swift
//  微博Demo
//
//  Created by 花化华 on 2016/11/27.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class WBNewFeatureView: WBBaseView {

    //创建scrollView
    lazy var scrollView: UIScrollView = {
        let scrollView = UIScrollView()
        
        //属性设置
        scrollView.bounces = false
        scrollView.delegate = self
        scrollView.isPagingEnabled = true
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.frame = self.bounds
        
        return scrollView
    }()
    
    //创建pageControl
    lazy var pageControl: UIPageControl = {
        let pageControl = UIPageControl()
        
        //属性设置
        pageControl.currentPageIndicatorTintColor = globalColor
        pageControl.pageIndicatorTintColor = UIColor.white
        pageControl.numberOfPages = 4
        pageControl.currentPage = 0
        
        return pageControl
    }()
    
    override func wbSetupSubviews() {
        super.wbSetupSubviews()
        setupUI()
    }

}

extension WBNewFeatureView {
    fileprivate func setupUI () {
        //设置View属性
        self.frame = screenBounds
        self.backgroundColor = UIColor.clear
        
        //添加子控件
        addSubview(scrollView)
        addSubview(pageControl)
        
        //scrollView添加imageView
        for i in 1...4 {
            let imageView = UIImageView(imageName: "new_feature_\(i)")
            imageView.frame = scrollView.frame.offsetBy(dx: screenWidth*CGFloat(i-1), dy: 0)
            scrollView.addSubview(imageView)
        }
        
        //scrollView设置内容大小
        scrollView.contentSize = CGSize(width: screenWidth*5, height: screenHeight)
        
        //约束
        pageControl.snp.makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.bottom.equalTo(self).offset(-100)
        }
        
    }
}


// MARK: - scrollViewDelegate
extension WBNewFeatureView: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offset = scrollView.contentOffset.x
        
        //四舍五入算法
        let currentPage = Int(offset/screenWidth + 0.5)
        pageControl.currentPage = currentPage
        
        //当最后一张滑过屏幕时隐藏pageControl
        pageControl.isHidden = offset > screenWidth*3.2
        
        //滑出屏幕时释放
        if offset >= screenWidth*4 {
            self.removeFromSuperview()
        }
    }
}
